package com.dhecp.project.business.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductInfo;
import com.dhecp.project.business.mapper.ProductInfoMapper;
import com.dhecp.project.business.service.ProductInfoService;
import com.dhecp.project.common.domain.DataBaseMessage;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 产品表  业务实现层
 * @author DH-Xxj
 * @version 2019年11月12日
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {

	@Autowired
	private ProductInfoMapper productInfoMapper;

	@Autowired
	private SysDictionaryForFieldService dictionaryForFieldService;
	
	/**
	 * 查询所有产品信息
	 * @param params
	 * @return List-ProductInfo
	 * @author lwl
	 * @throws Exception 
	 */
	@Override
	public List<ProductInfo> queryProductInfo(Map<String, Object> params) throws Exception{
		params.put("wherestr", dictionaryForFieldService.getWhereStr(params));

		if (params.get("field") == null || params.get("field") == ""){
			String orderBy = "GBrand,GID,GModel asc";
			PageUtils.startPageOrder(orderBy);
		}else{
			PageUtils.startPage();	
		}	
		
		return productInfoMapper.findProductInfo(params);
	}
	
	/**
	 * 通过guid查询单条记录
	 * @param guid
	 * @return 实体ProductInfo
	 * @author lwl
	 */
	@Override
	public ProductInfo queryProductInfoByGuid(String guid) {
		return productInfoMapper.findProductInfoByGuid(guid);
	}

	/**
	 * 匹配产品信息
	 * @param productInfoItems 必要参数：对应实体类的json格式字符串（包括：matchIid【必要，页面中行号】,gBrand,gID,gModel,gName,gSerial,gUnit）
	 * @return List - ProductInfo
	 * @throws Exception
	 * @author DH-Xxj
	 */
	@Override
	public List<ProductInfo> matchProductInfo(Map<String, Object> params) throws Exception{
		if (params.get("productInfoItems") == null || params.get("productInfoItems") == ""){
			throw new RuntimeException("请提供需要匹配的产品信息json格式字符串【productInfoItems】。");
		}
		List<ProductInfo> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductInfo.class);
		List<ProductInfo> matchProductInfoList = new ArrayList<ProductInfo>();
		List<String> matchIidList = new ArrayList<String>();
		Map<String, Object> matchIidMap = new HashMap<String, Object>();
		String repeatMatchIids = "";
		
		if (productInfoList == null || productInfoList.size() == 0){
			throw new RuntimeException("请提供要匹配的型号[必要]，以及品牌[可选]、品名[可选]、系列[可选]、规格[可选]、单位[可选]。");
		}
		for(ProductInfo productInfo : productInfoList){
			if ("".equals(productInfo.getMatchIid().toString())){
				throw new RuntimeException("匹配的行号不能为空，请修改后重新匹配。");
			}else{
				matchIidList.add(productInfo.getMatchIid().toString());
			}
		}
		if (matchIidList == null || matchIidList.size() == 0){
			throw new RuntimeException("请提供需要匹配的产品信息。");
		}else {
			for (String matchIid : matchIidList){
				if (matchIidMap.containsKey(matchIid)){
					if ("".equals(repeatMatchIids)){
						repeatMatchIids = matchIid;
					}else{
						repeatMatchIids = repeatMatchIids + ',' + matchIid;
					}
				}else{
					matchIidMap.put(matchIid, matchIid);
				}
			}
		}
		
		if (!"".equals(repeatMatchIids)){
			throw new RuntimeException("行号重复，请修改后重新匹配；重复行号【" + repeatMatchIids + "】");
		}
		
		for(ProductInfo productInfo : productInfoList){
			ProductInfo matchProductInfo = productInfoMapper.matchProductInfo(productInfo);
			if (matchProductInfo != null){
				matchProductInfoList.add(matchProductInfo);
			}
		}
		return matchProductInfoList;
	}
	
	/*@Override
	public AjaxResult importProduct(List<ProductInfo> productList,boolean isUpdateSupport) {
		if (productList == null || productList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
		for(ProductInfo productInfo:productList){
			if (productInfoMapper.findProductInfoByGBrand(productInfo)==null) {
				productInfo.setCreateUser(ShiroUtils.getUserId());
				productInfo.setCreateTime(new Date());
				productInfoMapper.insertProductInfo(productInfo);
				return AjaxResult.success("导入成功");
			}else if(isUpdateSupport){
				productInfo.setUpdateUser(ShiroUtils.getUserId());
				productInfo.setUpdateTime(new Date());
				productInfoMapper.updateProduct(productInfo);
				return AjaxResult.success("更新成功");
			}else{
				return AjaxResult.error("产品已存在");
			}
		}
		
		return AjaxResult.success("数据已全部导入成功");
	}*/
	
	
	/**
	 * 新增产品信息
	 * @param productInfoItems
	 * @param fSl   面价（含税/未税）计算税率
	 * @param fType 面价（含税/未税）计算类型：（fType == 1：含税面价计算未税面价，fType == 0：未税面价计算含税面价）
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult insertProduct(Map<String, Object> params) {
		if (StringUtils.isEmpty(params)) {
			return AjaxResult.error("数据提交失败，必填参数有误！");
		}
		if (params.get("vCpFl") == null || params.get("vCpFl") == ""){
			return AjaxResult.error("请将选择产品分类！");
		}
		Double fSl = 0.0;
		Integer fType = 2;		
		if (params.get("fSl") != null && params.get("fSl") != ""){
			fSl = Double.valueOf(params.get("fSl").toString());
		}
		if (params.get("fType") != null && params.get("fType") != ""){
			fType = Integer.valueOf(params.get("fType").toString());
		}
		List<ProductInfo> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductInfo.class);
		if (productInfoList == null || productInfoList.size() == 0) {
			return AjaxResult.error("请添加需要保存的产品信息。");
		}

		for (ProductInfo productInfo : productInfoList) {
			AjaxResult ajaxResult = checkedProductKey(productInfo);
			if (!"0".equals(ajaxResult.get("code").toString())){
				return ajaxResult;
			}
		}
		
		for (ProductInfo productInfo : productInfoList) {
			productInfo.setvCpFl(params.get("vCpFl").toString());
			productInfo.setCreateUser(ShiroUtils.getUserId());
			productInfo.setCreateTime(new Date());
			if (fType == 1){	//含税面价计算未税面价
				if(productInfo.getfHsMj() == null)productInfo.setfHsMj(0.00);
				productInfo.setfWsMj(productInfo.getfHsMj()*100/(100+fSl));
			}
			if (fType == 0){	//未税面价计算含税面价
				if(productInfo.getfWsMj() == null)productInfo.setfWsMj(0.00);
				productInfo.setfHsMj(productInfo.getfWsMj()*(100+fSl)/100);
			}
			if (productInfoMapper.findProductInfoByGBrand(productInfo) != null){
				productInfoMapper.updateProduct(productInfo);
			}else{
				productInfoMapper.insertProductInfo(productInfo);
			}
		}
		return AjaxResult.success("操作成功");
	}
	
	/**
	 * 清理产品导入过渡表中遗留的数据
	 * @param params
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult cleanProductInfoImport(Map<String, Object> params) {
		params.put("sessionId", ShiroUtils.getSessionId());
		DataBaseMessage dataBaseMessage = productInfoMapper.cleanProductInfoImport(params);
		
		if ("0".equals(dataBaseMessage.getCode())){
			return AjaxResult.success(dataBaseMessage.getMsg());
		}else if ("301".equals(dataBaseMessage.getCode())){
			return AjaxResult.warn(dataBaseMessage.getMsg());
		}else if ("500".equals(dataBaseMessage.getCode())){
			return AjaxResult.error(dataBaseMessage.getMsg());
		}else{
			return AjaxResult.error("未知服务器错误，请重试。");
		}
	}

	/**
	 * 将本次导入的产品数据从产品导入过渡表中转入产品信息正式表
	 * @param records 导入总记录数int类型
	 * @return AjaxResult
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult importToProductInfo(Map<String, Object> params) {
		params.put("sessionId", ShiroUtils.getSessionId());
		if (params.get("records") == null){
			params.put("records", 0);
		}
		DataBaseMessage dataBaseMessage = productInfoMapper.importToProductInfo(params);
		
		if ("0".equals(dataBaseMessage.getCode())){
			return AjaxResult.success(dataBaseMessage.getMsg());
		}else if ("301".equals(dataBaseMessage.getCode())){
			return AjaxResult.warn(dataBaseMessage.getMsg());
		}else if ("500".equals(dataBaseMessage.getCode())){
			return AjaxResult.error(dataBaseMessage.getMsg());
		}else{
			return AjaxResult.error("未知服务器错误，请重试。");
		}
	}
	
	/**
	 * 导入产品信息至产品信息过渡表
	 * @param productInfoItems
	 * @param fSl   面价（含税/未税）计算税率
	 * @param fType 面价（含税/未税）计算类型：（fType == 1：含税面价计算未税面价，fType == 0：未税面价计算含税面价）
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult importProduct(Map<String, Object> params) {
		if (StringUtils.isEmpty(params)) {
			return AjaxResult.error("数据提交失败，必填参数有误！");
		}
		Double fSl = 0.0;
		Integer fType = 2;		
		if (params.get("fSl") != null && params.get("fSl") != ""){
			fSl = Double.valueOf(params.get("fSl").toString());
		}
		if (params.get("fType") != null && params.get("fType") != ""){
			fType = Integer.valueOf(params.get("fType").toString());
		}
		List<ProductInfo> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductInfo.class);
		if (productInfoList == null || productInfoList.size() == 0) {
			return AjaxResult.error("数据包格式有误，请检查！");
		}

		for (ProductInfo productInfo : productInfoList) {
			AjaxResult ajaxResult = checkedProductKey(productInfo);
			if (!"0".equals(ajaxResult.get("code").toString())){
				return ajaxResult;
			}
		}

		for (ProductInfo productInfo : productInfoList) {
			productInfo.setCreateUser(ShiroUtils.getUserId());
			productInfo.setCreateTime(new Date());
			productInfo.setSessionId(ShiroUtils.getSessionId());
			if (fType == 1){	//含税面价计算未税面价
				if(productInfo.getfHsMj() == null)productInfo.setfHsMj(0.00);
				productInfo.setfWsMj(productInfo.getfHsMj()*100/(100+fSl));
			}
			if (fType == 0){	//未税面价计算含税面价
				if(productInfo.getfWsMj() == null)productInfo.setfWsMj(0.00);
				productInfo.setfHsMj(productInfo.getfWsMj()*(100+fSl)/100);
			}
			productInfoMapper.importProductInfo(productInfo);
		}
		return AjaxResult.success("操作成功");
	}

	/**
	 * 修改产品信息
	 * @param productInfoItems
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult updateProduct(Map<String, Object> params) {
		List<ProductInfo> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductInfo.class);
		if (productInfoList == null || productInfoList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
		
		for (ProductInfo productInfo : productInfoList) {
			productInfo.setUpdateUser(ShiroUtils.getUserId());
			productInfo.setUpdateTime(new Date());			
			if (productInfoMapper.findProductInfoByGBrandAndGuid(productInfo) != null) {
				return AjaxResult.error("已有相同【品牌、型号、规格、单位】的产品信息，请检查！");
			}else{
				productInfoMapper.updateProduct(productInfo);
			}
		}
		return AjaxResult.success("操作成功！");
	}

	/**
	 * 通过Guid删除产品信息
	 * @param productInfoItems
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult deleteProductInfoByGuid(Map<String, Object> params) {
		List<ProductInfo> productInfoList = JSON.parseArray(params.get("productInfoItems").toString(), ProductInfo.class);
		if (productInfoList == null || productInfoList.size() == 0) {
			return AjaxResult.error("数据包格式有误，请检查！");
		}
		for (ProductInfo productInfo : productInfoList) {
			productInfoMapper.deleteByGuid(productInfo);
		}
		return AjaxResult.success("操作成功");
	}

	/**
	 * 验证产品主键是否为空
	 * @param productInfo
	 * @return
	 * @author DH-Xxj
	 */
	private AjaxResult checkedProductKey(ProductInfo productInfo){
		String gModel = productInfo.getgModel();
		if (StringUtils.isEmpty(gModel)){
			productInfo.setgModel("常规");
		}
		if (StringUtils.isEmpty(productInfo.getgBrand()) || StringUtils.isEmpty(productInfo.getgID()) || StringUtils.isEmpty(productInfo.getgUnit())){
			return AjaxResult.error("【品牌、型号、单位】不能为空，请删除或修改存在空值的产品信息。");
		}
		return AjaxResult.success();
	}
	
}
